@using System.Text
@using Radzen.Blazor.Rendering
@using Microsoft.JSInterop
@inherits RadzenHtmlEditorButtonBase
@inject DialogService DialogService

<EditorButton Title=@Title Click=@OnClick Icon="insert_link" />

@code {
    protected override async Task OnClick()
    {
        await Editor.SaveSelectionAsync();

        bool blank = false;

        var attributes = await Editor.GetSelectionAttributes<LinkAttributes>("a", new[] {"innerText", "href", "target" });

        if (attributes.Target == "_blank")
        {
            blank = true;
        }

        var result = await DialogService.OpenAsync(Title, ds => @<div class="rz-html-editor-dialog">
            <RadzenTemplateForm TItem="LinkAttributes" Data="@attributes" Submit="() => ds.Close(true)">
                <div class="rz-html-editor-dialog-item">
                    <label>@UrlText</label>
                    <RadzenTextBox @bind-Value=@attributes.Href style="width: 100%" />
                </div>
                @if (string.IsNullOrWhiteSpace(attributes.InnerHtml) || attributes.InnerHtml == "<br>")
                {
                <div class="rz-html-editor-dialog-item">
                    <label>@LinkText</label>
                    <RadzenTextBox @bind-Value=@attributes.InnerText style="width: 100%" />
                </div>
                }
                <div class="rz-html-editor-dialog-item">
                    <RadzenCheckBox @bind-Value=@blank />
                    <label>@OpenInNewWindowText</label>
                </div>
                <div class="rz-html-editor-dialog-buttons">
                    <RadzenButton Text=@OkText ButtonType="ButtonType.Submit" />
                    <RadzenButton Text=@CancelText Click="()=> ds.Close(false)" ButtonStyle="ButtonStyle.Secondary" />
                </div>
            </RadzenTemplateForm>
        </div>);

        await Editor.RestoreSelectionAsync();

        if (result == true && !String.IsNullOrEmpty(attributes.Href))
        {
            var html = new StringBuilder();
            html.AppendFormat("<a href=\"{0}\"", attributes.Href);
            if (blank)
            {
                html.Append(" target=\"_blank\"");
            }

            html.AppendFormat(">{0}</a>", string.IsNullOrEmpty(attributes.InnerText) ? attributes.InnerHtml : attributes.InnerText);

            await Editor.ExecuteCommandAsync("insertHTML", html.ToString());
        }
    }
}